/**
 * 
 */
package com.jolestar.yayaweibotong.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.PropertyConfiguration;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

import com.jolestar.yayaweibotong.ServiceType;
import com.jolestar.yayaweibotong.YaYaAccessToken;
import com.jolestar.yayaweibotong.YaYaRequestToken;
import com.jolestar.yayaweibotong.YayaException;
import com.jolestar.yayaweibotong.service.OAuthService;

/**
 * @author jolestar@gmail.com
 * 
 */
public class TwitterOAuthService extends AbstractOAuthService {

	TwitterFactory factory = new TwitterFactory();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.service.OAuthService#request(javax.servlet
	 * .http.HttpServletRequest)
	 */
	@Override
	public YaYaRequestToken request(HttpServletRequest request) {
		Twitter twitter = factory.getOAuthAuthorizedInstance(
				ServiceType.twitter.getApiKey(),
				ServiceType.twitter.getApiSecret());
		try {
			RequestToken token = twitter.getOAuthRequestToken(this
					.generateCallback(request, ServiceType.twitter));
			return new YaYaRequestToken(token.getToken(),
					token.getTokenSecret(), token.getAuthorizationURL());
		} catch (TwitterException e) {
			throw new YayaException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.service.OAuthService#requestAccessToken(com
	 * .jolestar.yayaweibotong.YaYaRequestToken, java.lang.String)
	 */
	@Override
	public YaYaAccessToken requestAccessToken(YaYaRequestToken requestToken,
			String verifier) {
		if(StringUtils.isBlank(verifier)){
			throw new YayaException("verifier 码不能为空。");
		}
		Twitter twitter = factory.getOAuthAuthorizedInstance(
				ServiceType.twitter.getApiKey(),
				ServiceType.twitter.getApiSecret());
		try {
			AccessToken token = twitter.getOAuthAccessToken(
					requestToken.getToken(), requestToken.getTokenSecret(),
					verifier);
			return new YaYaAccessToken(token.getToken(),
					token.getTokenSecret(),
					Integer.toString(token.getUserId()), token.getScreenName());
		} catch (TwitterException e) {
			throw new YayaException(e);
		}
	}

}
